package com.vip.seata.at.business.util.feign;

import brave.Tracing;
import brave.propagation.B3Propagation;
import brave.propagation.ExtraFieldPropagation;
import com.alibaba.fastjson.JSON;
import com.vip.seata.at.business.util.ApplicationHelper;
import com.vip.seata.at.business.util.SleuthHelper;
import com.vip.seata.at.business.util.StringPool;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author : evan.liu
 * @version V1.0
 * @Description: TODO RestTemplate 添加请求信息
 * @date Date : 2022年05月16日 12:00 上午
 */
@Slf4j
@Component
@ConditionalOnProperty(value = "feign.traceable.enabled",havingValue = "true",matchIfMissing = false)
public class FeignTraceInterceptor implements RequestInterceptor {

    @Bean
    public Tracing tracing() {
        return Tracing.newBuilder().propagationFactory(
                ExtraFieldPropagation.newFactoryBuilder(B3Propagation.FACTORY)
                        .addField(SleuthHelper.SLEUTH_DEFAULT_BAGGAGE)
                        .build()
        ).build();
    }

    /**
     * 发起请求添加请求来源信息
     * @param template
     */
    @SneakyThrows
    @Override
    public void apply(RequestTemplate template) {
        log.info("Sleuth:{}",SleuthHelper.getSleuthTraceId());
        String application = ApplicationHelper.getApplicationName();
        String origin = SleuthHelper.getBaggageValue(StringPool.RPC_Origin_Application);
        if(StringUtils.isEmpty(origin)){
            SleuthHelper.addBaggage(StringPool.RPC_Origin_Application,application);
        }
        // FEIGN_Referer_Application 默认覆盖
        SleuthHelper.addBaggage(StringPool.RPC_Referer_Application,application);
        SleuthHelper.addBaggage(StringPool.RPC_Mode,StringPool.RPC_Mode_Http);
    }
}
